import json
import logging
import os
import traceback
from flask import request
from flask_restful import Resource, reqparse
import urllib.parse
from app.commons.check_token import checkIfLogin
from app.commons.ma import ma
from app.service.merge_data.functions import merge_filename

parser = reqparse.RequestParser(trim=True)


class ConfigRequestArgs(ma.Schema):
    date = ma.String()


class UploadConfigView(Resource):

    @staticmethod
    def delete_file(directory, full_filename, filename):
        if os.path.exists(os.path.join(directory, full_filename)):
            os.remove(os.path.join(directory, full_filename))
        elif os.path.exists(os.path.join(directory, filename)):
            os.remove(os.path.join(directory, full_filename))
        else:
            return

    def get(self):
        try:
            host="pjsnkr"
            query_args = ConfigRequestArgs().dump(request.args)
            cookie = urllib.parse.unquote(str(request.cookies.get('pj_login')))
            userid = checkIfLogin(cookie)
            if userid and str(userid)==host:
                date = str(query_args["date"])
                files = 'files/config/' + merge_filename("data_config.json", date)
                if not os.path.isfile(files):
                    with open('data_config.json', 'r', encoding='utf-8') as f:
                        conf = json.load(f)
                    f.close()
                    logging.warning("config doesn't exist, loading default")
                    return {"code": 0, "msg": "", "data": conf, "success": "true"}
                else:
                    with open(files, 'r', encoding='utf-8') as f:
                        conf = json.load(f)
                    f.close()
                    return {"code": 0, "msg": "", "data": conf, "success": "true"}
            else:
                return {"code": 0, "msg": "", "data": "", "success": "false"}
        except Exception as e:
            logging.warning("Exception when calling /api/config GET")
            traceback.print_exc()
            return {"code": 500, "msg": "服务器内部错误，请管理员查看路径是否存在，或先上传文件即可新建路径"}

    def post(self):
        try:
            cookie = urllib.parse.unquote(str(request.cookies.get('pj_login')))
            userid=checkIfLogin(cookie)
            host="pjsnkr"
            if userid and str(userid)==host:
                recv_data = request.get_json()
                date = recv_data["date"].replace("%20", " ")
                data = recv_data["data"]
                with open('data_config.json', 'r', encoding='utf-8') as f:
                    conf = json.load(f)
                f.close()
                conf["CurrentStockMap"] = data["CurrentStockMap"]
                conf["RequirementMap"] = data["RequirementMap"]
                conf["ExportColumns"] = data["ExportColumns"]
                with open("files/config/" + merge_filename("data_config.json", date), "w") as f:
                    f.write(json.dumps(conf))
                f.close()
                return {"success": "true"}
            else:
                return {"success": "false", "err_msg": "no login"}
        except:
            logging.warning("fail uploading config")
            return {"success": "false"}
